#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    this->list_up_timer=new QTimer(this);
    connect(this->list_up_timer,&QTimer::timeout,this,&MainWindow::onl_window_update_kk);
    this->list_up_timer->start(5000);

    server = new serverManager(this);
    server->setIp("127.0.0.1");
    server->setPort(8888);
    server->start_listen();

    dbhelper::getInstance();

    this->onl_user_window_list_init();//已注册用户状态显示
    connect(this->server,&serverManager::new_client,this,&MainWindow::on_newClient);
    //在线用户列表获取方式错误
    connect(this->server,&serverManager::new_onlUser,this,&MainWindow::on_newOnlUser);
    connect(this->server,&serverManager::onlUserOff,this,&MainWindow::on_OnlUserOff);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onl_user_window_list_init()
{
    this->my_model=new QSqlTableModel(this);
    this->my_model->setTable("userinfo");
    this->my_model->select();
    ui->onl_user_view->setModel(this->my_model);
    for(int i=0;i<this->my_model->columnCount();i++)
    {
        ui->onl_user_view->resizeColumnToContents(i);
    }
}

void MainWindow::onl_window_update_kk()
{
    //qDebug()<<"已进入更新用户列表";
    this->my_model->select();
    ui->onl_user_view->setModel(this->my_model);
    for(int i=0;i<this->my_model->columnCount();i++)
    {
        ui->onl_user_view->resizeColumnToContents(i);
    }
    //qDebug()<<"已更新用户列表";
}

void MainWindow::on_newClient(clientHandelr *handler)
{
    connect(handler,&clientHandelr::update_onl,this,&MainWindow::onl_window_update_kk);
    connect(handler,&clientHandelr::clcFile,this,&MainWindow::onclcFile);
    connect(handler,&clientHandelr::setFile,this,&MainWindow::onsetFile);
    connect(handler,&clientHandelr::setVideoList,this,&MainWindow::onsetVideoList);
}
//注释掉获取在线列表的错误获取
void MainWindow::on_newOnlUser(QString name)
{
    ui->onl_users_list_w->addItem(name);
}

void MainWindow::on_OnlUserOff(QString name)
{
    QList<QListWidgetItem *> off_user=ui->onl_users_list_w->findItems(name,Qt::MatchExactly);
    if(!off_user.isEmpty())
    {
        delete off_user.takeFirst();
    }
}

void MainWindow::onclcFile()
{
    ui->file_list_w->clear();
}

void MainWindow::onsetFile(QString file)
{
    ui->file_list_w->addItem(file);
}

void MainWindow::onsetVideoList(QString listt)
{
    ui->video_w->addItem(listt);
}

